<template>
  <div>
    <div class="content" id="js-drop-zone">
      <!--<div class="message intro">
        <div class="note">
          Drop BPMN diagram from your desktop or <a id="js-create-diagram" href>create a new diagram</a> to get started.
        </div>
      </div>-->
      <div class="canvas" id="js-canvas"></div>
      <div class="properties-panel-parent" id="js-properties-panel"></div>
    </div>

    <ul class="buttons">
      <li>
        <a id="js-download-diagram" href title="下载BPMN图表"> BPMN图表 </a>
        <!--<button id="js-download-diagram">BPMN图表</button>-->
      </li>
      <li>
        <a id="js-download-svg" href title="下载SVG图片">SVG图片</a>
        <!--<button id="js-download-svg">SVG图片</button>-->
      </li>
      <li>
        <button id="btn_save">保存</button>
      </li>
      <li>
        <button id="btn_deploy">部署</button>
      </li>
    </ul>

  </div>
</template>

<script>
  import $ from 'jquery';
  import BpmnModeler from 'bpmn-js/lib/Modeler';

  import propertiesPanelModule from 'bpmn-js-properties-panel';
  import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda';
  import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';
  import debounce from 'lodash/function/debounce';
  /*import {
    debounce
  } from 'min-dash';*/

  export default {
    name: 'Diagram',
    data() {
      return {
        name: 'a',
        description: 'a',
        bpmnModeler: null,
        bpmn: null,
      }
    },
    created: function () {
      console.log("created");
      var that = this;
      var canvas = $('#js-canvas');
      that.bpmnModeler = new BpmnModeler({
        container: canvas,
        propertiesPanel: {
          parent: '#js-properties-panel'
        },
        additionalModules: [
          propertiesPanelModule,
          propertiesProviderModule
        ],
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        }
      });
    },
    mounted() {
      console.log("mounted");
      var that = this;

      this.initPage();
      this.checkFileApi();
      this.diagramFunction();
      var downloadLink = $('#js-download-diagram');
      var downloadSvgLink = $('#js-download-svg');
      var exportArtifacts = debounce(function () {

        that.saveSVG(function (err, svg) {
          that.setEncoded(downloadSvgLink, 'diagram.svg', err ? null : svg);
        });

        that.saveDiagram(function (err, xml) {
          that.setEncoded(downloadLink, 'diagram.bpmn', err ? null : xml);
        });
      }, 500);
      that.bpmnModeler.on('commandStack.changed', exportArtifacts);
    },
    methods: {
      initPage() {
        console.log("initPage");
        const that = this;
        var name = 'myProcess';
        var description = 'myProcess';
        //  import diagramXML from '/static/resources/newDiagram.bpmn';

        var diagramXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:activiti=\"http://activiti.org/bpmn\" xmlns:bpmndi=\"http://www.omg.org/spec/BPMN/20100524/DI\" xmlns:omgdc=\"http://www.omg.org/spec/DD/20100524/DC\" xmlns:omgdi=\"http://www.omg.org/spec/DD/20100524/DI\" xmlns:bpmn2=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" xmlns:dc=\"http://www.omg.org/spec/DD/20100524/DC\" xmlns:di=\"http://www.omg.org/spec/DD/20100524/DI\" typeLanguage=\"http://www.w3.org/2001/XMLSchema\" expressionLanguage=\"http://www.w3.org/1999/XPath\" targetNamespace=\"http://bpmn.io/schema/bpmn\" xsi:schemaLocation=\"http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd\" id=\"sample-diagram\">\n  " +
          "<process id=\"myProcess\" name=\"" + name + "\" isExecutable=\"true\">\n  " +
          "<documentation>" + description + "</documentation>\n  <startEvent id=\"startevent1\" name=\"Start\"></startEvent>\n  </process>\n  <bpmndi:BPMNDiagram id=\"BPMNDiagram_myProcess\">\n    <bpmndi:BPMNPlane bpmnElement=\"myProcess\" id=\"BPMNPlane_myProcess\">\n      <bpmndi:BPMNShape bpmnElement=\"startevent1\" id=\"BPMNShape_startevent1\">\n        <omgdc:Bounds height=\"35.0\" width=\"35.0\" x=\"420.0\" y=\"250.0\"></omgdc:Bounds>\n      </bpmndi:BPMNShape>\n    </bpmndi:BPMNPlane>\n  </bpmndi:BPMNDiagram>\n</definitions>";

        var container = $('#js-drop-zone');

        var canvas = $('#js-canvas');

        // that.bpmn = new Bpmn({container:'#js-canvas'});

        that.bpmnModeler = new BpmnModeler({
          container: canvas,
          propertiesPanel: {
            parent: '#js-properties-panel'
          },
          additionalModules: [
            propertiesPanelModule,
            propertiesProviderModule
          ],
          moddleExtensions: {
            camunda: camundaModdleDescriptor
          }
        });

        this.createNewDiagram();
      },
      createNewDiagram() {
        console.log("createNewDiagram");
        var name = 'myProcess';
        var description = 'myProcess';
        //  import diagramXML from '/static/resources/newDiagram.bpmn';

        var diagramXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:activiti=\"http://activiti.org/bpmn\" xmlns:bpmndi=\"http://www.omg.org/spec/BPMN/20100524/DI\" xmlns:omgdc=\"http://www.omg.org/spec/DD/20100524/DC\" xmlns:omgdi=\"http://www.omg.org/spec/DD/20100524/DI\" xmlns:bpmn2=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" xmlns:dc=\"http://www.omg.org/spec/DD/20100524/DC\" xmlns:di=\"http://www.omg.org/spec/DD/20100524/DI\" typeLanguage=\"http://www.w3.org/2001/XMLSchema\" expressionLanguage=\"http://www.w3.org/1999/XPath\" targetNamespace=\"http://bpmn.io/schema/bpmn\" xsi:schemaLocation=\"http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd\" id=\"sample-diagram\">\n  <process id=\"myProcess\" name=\"" + name + "\" isExecutable=\"true\">\n  <documentation>" + description + "</documentation>\n  <startEvent id=\"startevent1\" name=\"Start\"></startEvent>\n  </process>\n  <bpmndi:BPMNDiagram id=\"BPMNDiagram_myProcess\">\n    <bpmndi:BPMNPlane bpmnElement=\"myProcess\" id=\"BPMNPlane_myProcess\">\n      <bpmndi:BPMNShape bpmnElement=\"startevent1\" id=\"BPMNShape_startevent1\">\n        <omgdc:Bounds height=\"35.0\" width=\"35.0\" x=\"420.0\" y=\"250.0\"></omgdc:Bounds>\n      </bpmndi:BPMNShape>\n    </bpmndi:BPMNPlane>\n  </bpmndi:BPMNDiagram>\n</definitions>";
        this.openDiagram(diagramXML);
      },
      openDiagram(xml) {
        console.log("openDiagram");
        var that = this;
        const container = $('#js-drop-zone');
        that.bpmnModeler.importXML(xml, function (err) {
          if (err) {
            container.removeClass('with-diagram').addClass('with-error');
            container.find('.error pre').text(err.message);
            console.error(err);
          } else {
            container.removeClass('with-error').addClass('with-diagram');
          }
        });
      },
      saveDiagram(done) {
        console.log("saveDiagram");
        var that = this;
        that.bpmnModeler.saveXML({format: true}, function (err, xml) {
          done(err, xml);
        });
      },
      saveSVG(done) {
        console.log("saveSVG");
        var that = this;
        that.bpmnModeler.saveSVG(done);
      },
      registerFileDrop(container, callback) {
        console.log("saveSVG");

        function handleFileSelect(e) {
          e.stopPropagation();
          e.preventDefault();

          var files = e.dataTransfer.files;

          var file = files[0];

          var reader = new FileReader();

          reader.onload = function (e) {

            var xml = e.target.result;

            callback(xml);
          };

          reader.readAsText(file);
        }

        function handleDragOver(e) {
          e.stopPropagation();
          e.preventDefault();

          e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
        }

        container.get(0).addEventListener('dragover', handleDragOver, false);
        container.get(0).addEventListener('drop', handleFileSelect, false);
      },
      checkFileApi() {
        console.log("checkFileApi");
        const container = $('#js-drop-zone');
        ////// file drag / drop ///////////////////////

        // check file api availability
        if (!window.FileList || !window.FileReader) {
          window.alert(
            'Looks like you use an older browser that does not support drag and drop. ' +
            'Try using Chrome, Firefox or the Internet Explorer > 10.');
        } else {
          this.registerFileDrop(container, this.openDiagram);
        }
      },
      diagramFunction() {
        console.log("diagramFunction");
        // bootstrap diagram functions

        $(function () {

          $('#js-create-diagram').click(function (e) {
            e.stopPropagation();
            e.preventDefault();

            createNewDiagram();
          });

          $('.buttons a').click(function (e) {
            if (!$(this).is('.active')) {
              e.preventDefault();
              e.stopPropagation();
            }
          });
        });
      },
      setEncoded(link, name, data) {
        console.log("setEncoded");
        var encodedData = encodeURIComponent(data);

        if (data) {
          link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
          });
        } else {
          link.removeClass('active');
        }
      },
    }
  }

</script>

<style scoped>
  #js-canvas {
    width: calc(100vw - 300px);
    height: calc(100vh - 130px);
  }

  #js-drop-zone {
    width: calc(100vw - 300px);
    height: calc(100vh - 130px);
  }

  #js-properties-panel {
    position: fixed;
    top: 50px;
    right: 0;
    height: calc(100vh - 90px);
    overflow-y: auto;
  }

  #js_bpmn_btns {

  }

  #js_bpmn_btns li {
    display: inline;
  }
</style>
